import { ApiCall } from "tsrpc";
import { ReqFollowTalks, ResFollowTalks } from "../../shared/protocols/talks/PtlFollowTalks";
import { Global } from '../../Global/index';
import upload from "../../utils/upload";
import { Folder } from "../../utils/Folder";
import { ObjectId } from "mongodb";
import { followTalks } from "../../shared/types/talks";

export default async function (call: ApiCall<ReqFollowTalks, ResFollowTalks>) {
    // TODO
    const { photos,context,mainTalk } = call.req
    const user = call.currentUser

    if(photos){
        try {
            const photoPaths:string[] = []
            // const photoPaths = new Array<string>()

            const promises = photos.map(async photo =>{
                const fileName = photo.fileName
                const index= fileName.lastIndexOf('.')
                const type = fileName.slice(index + 1)
                const typeCate = photo.fileType.slice(0,photo.fileType.indexOf('/')) 

                if(type.toLowerCase() !== 'png' && type.toLowerCase() !== 'jpg' ){
                    throw new Error('只能上传.jpg或.png文件')
                }

                const path = await upload({
                    folder:Folder.sources,
                    type,
                    typeCate,
                    id:new ObjectId
                },photo.fileData)

                photoPaths.push(path)
            })

            await Promise.all(promises)

            const followTalk:followTalks = {
                _id:new ObjectId,
                user,
                context,
                time :new Date,
                photos:photoPaths
            }

            const ret = await Global.collection('talks').updateOne({
                _id:mainTalk
            },{
                $push:{
                    follows:followTalk
                }
            })

            call.succ({
                followTalk:followTalk
            })
        } catch (error) {
            if(error instanceof Error){
                console.log(error);
                return call.error(error.message)
            }
        }

    }
    else{
        const followTalk:followTalks = {
            _id:new ObjectId,
            user,
            context,
            time :new Date,
        }

        const ret = await Global.collection('talks').updateOne({
            _id:mainTalk
        },{
            $push:{
                follows:followTalk
            }
        })


        call.succ({
            followTalk:followTalk
        })
    }

}